<template>
  <div class="form-style">
    <div class="login-con">
      <div class="login-block">{{ title }}</div>
      <div class="form-con">
        <img v-show="showLogo" src="/logo.png" />
        <el-form
          size="mini"
          label-position="right"
          label-width="83px"
          :class="loginCode?'myLoginForm':'loginForm'"
        >
          <el-form-item :label="$t('m.USER_NAME')">
            <el-input
              @keyup.enter.native="handleLogin"
              v-model="userName"
              :placeholder="$t('m.tip.LOGIN_USER_NAME_TIP')"
            ></el-input>
          </el-form-item>
          <el-form-item :label="$t('m.PASSWORD')" :class="loginCode ? 'aa':'formItem'">
            <el-input
              @keyup.enter.native="handleLogin"
              type="password"
              v-model="passWord"
              :placeholder="$t('m.tip.LOGIN_PASSWORD_TIP')"
            ></el-input>
          </el-form-item>
          <el-form-item label="验证码" v-if="loginCode" style="margin-bottom: 1px;">
            <el-input @keyup.enter.native="handleLogin" v-model="code" style="width:40%"></el-input>
            <el-button
              v-if="codeShow"
              style="margin-left:15px"
              type="primary"
              @click="getPhoneCode"
            >获取验证码</el-button>
            <el-button v-else style="margin-left:15px" type="primary">重新发送({{count}})</el-button>
          </el-form-item>
          <el-form-item style="margin-bottom: 1px;">
            <el-checkbox v-model="checked">{{$t('m.REMEMBER_THE_PASSWORD')}}</el-checkbox>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="handleLogin">{{$t('m.LOGIN')}}</el-button>
            <el-button type="danger" style="margin-left: 30%" @click="reset">{{$t('m.RESET')}}</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div class="footer">
        <div class="copyright">{{ companyName }}</div>
        <div class="advice">{{$t('m.LOGIN_TIPS')}}</div>
      </div>
    </div>
  </div>
</template>
<script>
import { login, forceLogout, getOperator, verificationcode } from '@/api/user'
import { initSDK } from '@/utils/SDK'
import { reqFullScreen } from '@/utils/util'
import CryptoJS from 'crypto-js'
export default {
  name: 'login',
  data() {
    return {
      userName: '',
      passWord: '',
      code: '',
      title:
        localStorage.getItem('language') == 'zh-CN'
          ? projectTitle
          : projectTitle_en,
      companyName:
        localStorage.getItem('language') == 'zh-CN'
          ? companyName
          : companyName_en,
      showLogo: showLogo,
      codeShow: true, //判断显示隐藏
      count: '', //显示时的文字内容
      timer: null,
      loginCode: loginCode,
      checked: false,
    }
  },
  methods: {
    handleLogin() {
      let _this = this
      sessionStorage.clear()
      if (this.loginCode && this.code == '') {
        this.$message.error('请输入验证码')
        return
      }
      forceLogout({ username: this.userName }).then((res) => {
        let obj = {
          request: {
            '@id': '10000',
            '@type': 'UserLogin',
            userName: this.userName,
            userPwd: this.passWord,
          },
        }
        if (this.loginCode) {
          obj.request.verificatonCode = this.code
        }
        login(obj).then((res) => {
          if (res.data.msg == 'success') {
            localStorage.setItem('lockStatus', 0)
            sessionStorage.setItem('tokenSign', res.data.tokensign)
            sessionStorage.setItem('operatorid', res.data.operatorid)
            // 获取操作员信息
            getOperator()
              .then((res) => {
                this.$store.commit('SetOperatorInfo', res.data.eventdata)
                initSDK()
                //自动全屏
                reqFullScreen()
                // 记住密码，储存登录信息
                this.checked
                  ? this.handleSaveUsernameAndPwd()
                  : this.handleDelUsernameAndPwd()
                let isAdmin
                this.userName == 'admin' ? (isAdmin = 1) : (isAdmin = 0)
                sessionStorage.setItem('isAdmin', isAdmin)
                _this.$router.push({ name: 'home' })
              })
              .catch((err) => {
                this.$message({
                  showClose: true,
                  message: '获取操作员信息失败',
                  type: 'error',
                })
                console.log('获取操作员信息失败')
              })
          } else {
            let message = '登录失败'
            if (res.data.reason == 'wrong password') {
              message = '密码错误'
            } else if (res.data.reason == 'No_this_operator') {
              message = '该用户不存在'
            } else if (res.data.reason == 'verification_error') {
              message = '验证码错误'
            }
            this.$message({
              showClose: true,
              message: message,
              type: 'error',
            })
          }
        })
      })
    },
    reset() {
      this.userName = ''
      this.passWord = ''
      this.code = ''
    },
    compare(property) {
      return function (a, b) {
        var value1 = a[property]
        var value2 = b[property]
        return value1 - value2
      }
    },
    // 储存表单信息
    handleSaveUsernameAndPwd() {
      localStorage.setItem('web_userName', this.handleEncryption(this.userName))
      localStorage.setItem('web_passWord', this.handleEncryption(this.passWord))
      localStorage.setItem('web_remember', this.checked ? '1' : '0')
    },
    //移除
    handleDelUsernameAndPwd() {
      localStorage.removeItem('web_userName')
      localStorage.removeItem('web_passWord')
      localStorage.removeItem('web_remember')
    },
    // Encrypt 加密
    handleEncryption(message) {
      var cipherText = CryptoJS.AES.encrypt(message, 'microsys').toString()
      return cipherText
    },
    // Decrypt 解密
    handleDecode(message) {
      var bytes = CryptoJS.AES.decrypt(message, 'microsys')
      var originalText = bytes.toString(CryptoJS.enc.Utf8)
      return originalText
    },
    //点击获取验证码
    getPhoneCode() {
      if (this.userName == '' || this.passWord == '') {
        this.$message.warning('请输入用户名和密码')
        return
      }
      verificationcode({ operatorName: this.userName }).then((res) => {
        if (res.data.msg == 'succ') {
          console.log('验证码发送成功')
          const TIME_COUNT = 60 //倒计时60秒
          if (!this.timer) {
            this.count = TIME_COUNT
            this.codeShow = false
            this.timer = setInterval(() => {
              if (this.count > 0 && this.count <= TIME_COUNT) {
                this.count--
              } else {
                this.codeShow = true
                clearInterval(this.timer)
                this.timer = null
              }
            }, 1000)
          }
        } else {
          let message = '获取验证码失败'
          if (
            res.data.reason == "'NoneType' object has no attribute 'telphone'"
          ) {
            message = '该账户未配置手机号'
          }
          this.$message.warning(message)
          return
        }
      })
    },
  },
  mounted() {
    let userName = localStorage.getItem('web_userName')
    let passWord = localStorage.getItem('web_passWord')
    let checkedFlag = localStorage.getItem('web_remember')
    if (userName && passWord) {
      this.userName = this.handleDecode(userName)
      this.passWord = this.handleDecode(passWord)
      checkedFlag == 1 ? (this.checked = true) : (this.checked = false)
    }
  },
}
</script>

<style>
.form-style {
  width: 100%;
  height: 100%;
  background-image: url('../assets/images/login-bg.png');
  background-size: cover;
  background-position: center;
}
.login-con {
  width: 540px;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
.login-block {
  line-height: 74px;
  color: #fff;
  background-color: #3582b9;
  text-align: center;
  font-size: 25px;
}
.footer {
  background-color: #3582b9;
  height: 74px;

  color: #fff;
  /*flex 布局*/
  display: flex;
  flex-direction: column;
  /*实现垂直居中*/
  align-items: center;
  /*实现水平居中*/
  justify-content: center;
}
.copyright {
  height: 20px;
  font-size: 14px;
}
.advice {
  height: 20px;
  font-size: 11px;
  margin-top: 1%;
  text-align: center;
  padding: 0px 10px;
}
.form-con {
  height: 210px;
  background-color: #fff;
  position: relative;
}
.form-con img {
  position: absolute;
  top: 38px;
  left: 54px;
  height: 100px;
  width: 100px;
}
.myLoginForm {
  width: 274px;
  height: 200px;
  position: absolute;
  top: 20px;
  right: 100px;
}
.loginForm {
  width: 260px;
  height: 200px;
  position: absolute;
  top: 40px;
  right: 100px;
}
.formItem {
  margin-bottom: 1px !important;
}
</style>
